package api

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"one_exam/global"
	"one_exam/internal/model/dao"
	"one_exam/internal/model/service"
	"one_exam/internal/utils"
	"time"
)

type LoginForm struct {
	Mobile   string `form:"mobile" binding:"required" json:"mobile"`
	Password string `form:"password" binding:"required" json:"password"`
}

func Login(c *gin.Context) {
	var form LoginForm
	err := c.ShouldBind(&form)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "参数获取失败"})
		return
	}
	//用户是否存在
	var user dao.User
	user, b := service.CheckUserByMobile(form.Mobile)
	if !b {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "用户不存在"})
		return
	}
	//密码是否匹配
	if user.Password != form.Password {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "密码错误"})
		return
	}
	jwtSign := utils.NewJWT(global.Global.Jwt.SecretKey)
	jwtCustomClaims := utils.CustomClaims{
		ID: user.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + global.Global.Jwt.Expire,
			Subject:   "UserLogin",
		},
	}
	token, err := jwtSign.CreateToken(jwtCustomClaims)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "token创建失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"message": "登录成功",
		"token":   token,
	})

}
